﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkflowCore.Interface;
using WorkflowCore.Models;
using WorkflowCore.Service.Dto.Fundamentals;
using WorkflowCore.Service.Strps;
using WorkflowCore.Services;

namespace WorkflowCore.Service.Steps
{
    // 当驳回时执行的步骤
    public class RejectStep:StepBody
    {
        private readonly IWorkflowRegistry workflowRegistry;

        public RejectStep(IWorkflowRegistry workflowRegistry)
        {
            this.workflowRegistry = workflowRegistry;
        }

        public override ExecutionResult Run(IStepExecutionContext context)
        {
            var def = workflowRegistry.GetDefinition(context.Workflow.WorkflowDefinitionId, context.Workflow.Version);

            Console.WriteLine($"{context.Step.Name} 驳回");

            // 4.2 设置驳回路由
            var eventData = context.Item as WorkflowAuditInput;
            var nextStepId = nameof(EndStep);
            if (!string.IsNullOrWhiteSpace(eventData.RejectToStepId))
            {
                // 驳回到历史节点
                nextStepId = eventData.RejectToStepId;
            }
            context.Step.Outcomes.Clear();
            context.Step.Outcomes.Add(new ValueOutcome
            {
                ExternalNextStepId = nextStepId,
                NextStep = def.Steps.FirstOrDefault(p => p.ExternalId == nextStepId)!.Id
            });

            return ExecutionResult.Next();
        }
    }
}
